package com.cc.blog.web.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cc.blog.admin.mapper.ArticleMapper;
import com.cc.blog.admin.model.ArticleDO;
import com.cc.blog.common.model.BaseDO;
import com.cc.blog.common.utils.PageResult;
import com.cc.blog.common.utils.Result;
import com.cc.blog.web.convert.ArticleConvert;
import com.cc.blog.web.domain.dto.FindArchiveArticlePageListReqDTO;
import com.cc.blog.web.domain.vo.FindArchiveArticlePageListRspVO;
import com.cc.blog.web.domain.vo.FindArchiveArticleRspVO;
import com.cc.blog.web.service.ArchiveService;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.YearMonth;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * @Author cc
 * @Date 2024/7/16 15:26
 */
@Service
@Slf4j
@AllArgsConstructor
public class ArchiveServiceImpl implements ArchiveService {

    private final ArticleMapper articleMapper;

    @Override
    public Result findArchivePageList(FindArchiveArticlePageListReqDTO findArchiveArticlePageListReqDTO) {
        Long current = findArchiveArticlePageListReqDTO.getCurrent();
        Long size = findArchiveArticlePageListReqDTO.getSize();
        // 分页查询
        IPage<ArticleDO> page = articleMapper.selectPage(new Page<>(current,size), Wrappers.<ArticleDO>lambdaQuery().orderByDesc(BaseDO::getCreateTime));
        List<ArticleDO> articleDOS = page.getRecords();
        List<FindArchiveArticlePageListRspVO> vos = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(articleDOS)) {
            // DO 转 VO
            List<FindArchiveArticleRspVO> archiveArticleRspVOS =  articleDOS.stream()
                    .map(articleDO -> ArticleConvert.INSTANCE.convertDO2ArchiveArticleVO(articleDO))
                    .collect(Collectors.toList());
            // 按创建的月份进行分组
            Map<YearMonth, List<FindArchiveArticleRspVO>> map = archiveArticleRspVOS.stream().collect(Collectors.groupingBy(FindArchiveArticleRspVO::getCreateMonth));
            // 使用 TreeMap 按月份倒序排列
            Map<YearMonth, List<FindArchiveArticleRspVO>> sortedMap = new TreeMap<>(Collections.reverseOrder());
            sortedMap.putAll(map);
            // 遍历排序后的 Map，将其转换为归档 VO
            sortedMap.forEach((k, v) -> vos.add(FindArchiveArticlePageListRspVO.builder().month(k).articles(v).build()));
        }
        return PageResult.success(page, vos);
    }
}
